/**********************************************************

@description:
*File Name:graph.c
*Author: ydx
*mail: yudongxiang93@163.com
*Create Time: Wed 30 Apr 2025 10:53:12 PM CST
**********************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
//vexs not gothrough, the arc is MAX
//vexs gothrough with itself, the arc is 0
//
#define MAX 32767
typedef struct graph{
	char *vexs;
	int **arcs;
	int vex_num,arc_num;
}graph;
graph * init_graph(int vex_num){
	graph *g=(graph*)malloc(sizeof(graph));
	g->vexs=(char*)malloc(sizeof(char)*vex_num);
	g->arcs=(int**)malloc(sizeof(int*)*vex_num);
	for(int i=0;i<vex_num;i++){
		g->arcs[i]=(int*)malloc(sizeof(int)*vex_num);
	}
	g->vex_num=vex_num;
	g->arc_num=0;
	return g;
}
void createGraph(graph *g,char *vexs,int* arcs){
	for(int i=0;i<g->vex_num;i++){
		g->vexs[i]=vexs[i];
		for(int j=0;j<g->vex_num;j++){
			g->arcs[i][j]=*(arcs+i*g->vex_num+j);
			if(g->arcs[i][j] !=0 && g->arcs[i][j] != MAX){
				g->arc_num++;
			}
		}
	}
	g->arc_num/=2;
}
void dfs(graph *g,int* visited,int index){
	printf("%c\t",g->vexs[index]);
	visited[index]=1;
	for(int i=0;i<g->vex_num;i++){
		if(g->arcs[index][i]>0 && g->arcs[index][i] != MAX && !visited[i]){
			dfs(g,visited,i);
		}
	}
}
void print_aarr(int **arr,int leni,int lenj,char* name){
	printf("%s:\n",name);
	for(int i=0;i<leni;i++){
		for(int j=0;j<lenj;j++){
			printf("%4d ",arr[i][j]);
		}
		printf("\n");
	}
}
void floyd(graph* g,int index){
	int** d=(int**)malloc(g->vex_num*sizeof(int*));
	int** p=(int**)malloc(g->vex_num*sizeof(int));
	for(int i=0;i<g->vex_num;i++){
	    d[i]=(int*)malloc(g->vex_num*sizeof(int));
	    p[i]=(int*)malloc(g->vex_num*sizeof(int));
		for(int j=0;j<g->vex_num;j++){
			d[i][j]=g->arcs[i][j];
			if(g->arcs[i][j] >0 && g->arcs[i][j] != MAX){
				p[i][j] = i;
			}else{
				p[i][j]=-1;
			}
		}
	}
	print_aarr(d,g->vex_num,g->vex_num,"d:");
	print_aarr(p,g->vex_num,g->vex_num,"p:");
	print_aarr(g->arcs,g->vex_num,g->vex_num,"g->arcs:");
	for(int i=0;i<g->vex_num;i++){
		for(int j=0;j<g->vex_num;j++){
			for(int k=0;k<g->vex_num;k++){
				if(d[j][i]+d[i][k]<d[j][k]){
					d[j][k]=d[j][i]+d[i][k];
					p[j][k]=p[i][k];
				}
			}
		}
	}
	print_aarr(d,g->vex_num,g->vex_num,"d:");
	print_aarr(p,g->vex_num,g->vex_num,"p:");
}
int main(){
	graph* g=init_graph(4);
	int arcs[16]={
		0,  1,MAX,3,
		1,  0,  2,2,
		MAX,2,  0,8,
		3,  2,  8,0,
	};
	createGraph(g,"1234",arcs);

	printf("dfs:");
	int *visited=(int*)malloc(sizeof(int)*g->vex_num);
	memset(visited,0,g->vex_num*sizeof(int));
	dfs(g,visited,0);
	printf("\n");
	floyd(g,0);
	printf("\n");
	
}
